<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 编辑区域 -->
    <div v-if="showEditForm" class="mb-4">
      <a-card title="编辑活动" class="mb-4">
        <template #extra>
          <a-space>
            <a-button @click="cancelEdit">取消</a-button>
            <a-button type="primary" @click="saveEdit">保存</a-button>
          </a-space>
        </template>
        <a-spin
          :loading="editSpinLoading"
          :size="35"
          class="w-[100%]"
          tip="正在处理, 请稍候..."
        >
          <a-form
            ref="editFormRef"
            :model="editForm"
            :rules="editRules"
            auto-label-width
          >
            <div class="flex justify-between" style="flex-wrap: wrap">
              <a-form-item
                class="w-[100%]"
                field="activityTitle"
                label="活动标题"
                required
              >
                <a-input
                  v-model="editForm.activityTitle"
                  placeholder="活动标题"
                />
              </a-form-item>

              <a-form-item
                class="w-[33%]"
                field="activityTop"
                label="是否置顶"
                tooltip="置顶会让此活动展示在最前面"
              >
                <a-radio-group v-model="editForm.activityTop" type="button">
                  <a-radio
                    v-for="(item, index) in dicts[proxy.DICT.yesNo]"
                    :key="index"
                    :value="item.dictKey"
                    >{{ item.dictValue }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                class="w-[33%]"
                field="activitySort"
                label="排序值"
                tooltip="活动的展示顺序，数值越小排序越靠前"
              >
                <a-input-number
                  v-model="editForm.activitySort"
                  :min="0"
                  placeholder="排序值"
                />
              </a-form-item>
              <a-form-item
                class="w-[33%]"
                field="status"
                label="活动状态"
                required
              >
                <a-select
                  v-model="editForm.status"
                  allow-clear
                  placeholder="活动状态"
                >
                  <a-option
                    v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                    :key="index"
                    :label="d.dictValue"
                    :value="d.dictKey"
                  />
                </a-select>
              </a-form-item>

              <a-form-item
                class="w-[100%]"
                field="activityContent"
                label="活动内容"
                required
              >
                <tinymce-editor
                  ref="editEditorRef"
                  :editorHeight="300"
                  :file-source="fileSource.lindi_activity_content_file.key"
                />
              </a-form-item>
            </div>
          </a-form>
        </a-spin>
      </a-card>
    </div>
    <!-- 数据列表 -->
    <a-row
      v-if="!showEditForm"
      class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
    >
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form
          :model="searchForm"
          label-align="left"
          layout="inline"
          size="small"
        >
          <a-form-item field="activityTitle" label="活动标题">
            <a-input
              v-model="searchForm.activityTitle"
              placeholder="活动标题"
            />
          </a-form-item>
          <a-form-item field="status" label="活动状态">
            <a-select
              v-model="searchForm.status"
              allow-clear
              placeholder="活动状态"
            >
              <a-option
                v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                :key="index"
                :label="d.dictValue"
                :value="d.dictKey"
              />
            </a-select>
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
              :popup-visible="deleteConfirmVisible"
              content="确定删除选中活动吗?"
              type="warning"
              @cancel="onDeleteConfirmCancel"
              @ok="onDeleteConfirmOK"
            >
              <a-button
                status="danger"
                type="primary"
                @click="deleteBtnClick(selectedKeys)"
              >
                <template #icon>
                  <icon-delete />
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
            v-perm="['lindi:activity:add']"
            size="small"
            type="primary"
            @click="addBtnClick()"
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>添加</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button
            shape="circle"
            size="small"
            @click="showSearchRow = !showSearchRow"
          >
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          v-model:selectedKeys="selectedKeys"
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          :row-selection="rowSelection"
          :scroll="{ minWidth: 600, y: '100%' }"
          class="w-[100%]"
          row-key="activityId"
          table-layout-fixed
        >
          <!-- 活动标题 -->
          <template #activityTitle="{ record }">
            <a-link icon @click="detailBtnClick(record.activityId)"
              >{{ record.activityTitle }}
            </a-link>
          </template>

          <!-- 是否置顶 -->
          <template #activityTop="{ record }">
            <dict-convert
              :dict-data="dicts[proxy.DICT.yesNo]"
              :dict-key="record.activityTop"
            />
          </template>

          <!-- 活动状态 -->
          <template #status="{ record }">
            <dict-convert
              :dict-data="dicts[proxy.DICT.commonNumberStatus]"
              :dict-key="record.status"
            />
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-space>
              <a-button
                v-perm="['lindi:activity:update']"
                size="mini"
                type="text"
                @click="editBtnClick(record.activityId)"
              >
                <template #icon>
                  <icon-edit />
                </template>
                <template #default>编辑</template>
              </a-button>
              <a-popconfirm
                content="确认要删除吗?"
                @ok="deleteBtnOkClick(record.activityId)"
              >
                <a-button
                  v-perm="['lindi:activity:delete']"
                  size="mini"
                  status="danger"
                  type="text"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  <template #default>删除</template>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
          v-if="datatable.total > 0"
          v-model:page-num="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="datatable.total"
          @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
      v-model:visible="modal.visible"
      :esc-to-close="false"
      :footer="false"
      :mask-closable="false"
      :width="modal.width"
      draggable
    >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        v-if="modal.visible"
        :params="modal.params"
        @cancel="onCancel"
        @ok="onOk"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, shallowRef } from "vue";
import { useRouter } from "vue-router";
import {
  addActivityApi,
  deleteActivityByActivityIdApi,
  getPageActivityListApi,
  getActivityByActivityIdApi,
  updateActivityByActivityIdApi,
} from "~/api/lindi/activity.js";
import { fileAccept, fileListType, fileSource } from "~/utils/sys.js";

import TinymceEditor from "~/components/tinymceEditor/index.vue";
import ActivityDetail from "./ActivityDetail.vue";

//全局实例
const { proxy } = getCurrentInstance();
//路由实例
const router = useRouter();
//加载字典
const dicts = proxy.LoadDicts([
  proxy.DICT.commonNumberStatus,
  proxy.DICT.yesNo,
]);

// 编辑表单相关
const showEditForm = ref(false);
const editSpinLoading = ref(false);
const editFormRef = ref(null);
const editEditorRef = ref(null);

const currentEditActivityId = ref(null);

// 编辑表单数据
const editForm = reactive({
  activityId: null,
  activityTitle: null,
  activityContent: null,

  activityTop: proxy.yesNo.no.key,
  activitySort: null,
  publishTime: null,
  status: null,
});

// 编辑表单校验规则
const editRules = {
  activityTitle: [
    { required: true, message: "活动标题不能为空", trigger: "submit" },
  ],
  activityContent: [
    { required: true, message: "活动内容不能为空", trigger: "submit" },
  ],
  status: [{ required: true, message: "活动状态不能为空", trigger: "submit" }],
};

//是否展示搜索区域
const showSearchRow = ref(true);
//搜索参数表单
const searchForm = reactive({
  //活动标题
  activityTitle: null,
  //活动状态
  status: null,
  //页码
  pageNum: 1,
  //条数
  pageSize: 10,
});
//表格选中数据
const selectedKeys = ref([]);
//表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});
//数据列表
const datatable = reactive({
  //列配置
  columns: [
    {
      title: "活动标题",
      dataIndex: "activityTitle",
      slotName: "activityTitle",
      align: "center",
      width: 220,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: "是否置顶",
      dataIndex: "activityTop",
      slotName: "activityTop",
      align: "center",
      width: 90,
    },
    {
      title: "排序",
      dataIndex: "activitySort",
      align: "center",
      width: 90,
    },
    {
      title: "发布时间",
      dataIndex: "createTime",
      align: "center",
      width: 150,
    },
    {
      title: "活动状态",
      dataIndex: "status",
      slotName: "status",
      align: "center",
      width: 100,
    },
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  //加载
  loading: false,
  //数据列表
  records: [],
  //总条数
  total: 0,
});
//查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.activityTitle = null;
    searchForm.status = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }
  datatable.loading = true;
  getPageActivityListApi(searchForm)
    .then((res) => {
      datatable.records = res.records;
      datatable.total = res.total;
    })
    .finally(() => {
      datatable.loading = false;
    });
};
//公共模态框
const modal = reactive({
  //是否显示
  visible: false,
  //模态框标题
  title: "活动管理",
  //宽度
  width: "1000px",
  //传递参数
  params: {},
  //组件名称
  component: null,
});
//添加按钮 -> 点击事件
const addBtnClick = () => {
  currentEditActivityId.value = null;
  // 重置表单数据
  Object.keys(editForm).forEach((key) => {
    if (key === "activityTop") {
      editForm[key] = proxy.yesNo.no.key;
    } else if (key === "status") {
      editForm[key] = 1;
    } else {
      editForm[key] = null;
    }
  });

  // 清空编辑器内容
  if (editEditorRef.value) {
    editEditorRef.value.setEditorContent("");
  }
  showEditForm.value = true;
};
//编辑按钮 -> 点击事件
const editBtnClick = (activityId) => {
  currentEditActivityId.value = activityId;
  editSpinLoading.value = true;
  showEditForm.value = true;
  loadActivityForEdit(activityId);
};

// 加载活动详细信息用于编辑
const loadActivityForEdit = (activityId) => {
  if (!activityId) {
    proxy.$msg.error("活动ID不能为空");
    return;
  }

  editSpinLoading.value = true;

  // 获取活动详情
  getActivityByActivityIdApi(activityId)
    .then((res) => {
      if (res) {
        // 重置表单数据
        Object.keys(editForm).forEach((key) => {
          if (key === "activityTop") {
            editForm[key] = proxy.yesNo.no.key;
          } else {
            editForm[key] = null;
          }
        });

        // 数据赋值
        for (let key in res) {
          if (editForm.hasOwnProperty(key)) {
            editForm[key] = res[key];
          }
        }

        // 富文本内容需要延迟设置，确保编辑器已初始化
        if (res.activityContent) {
          setTimeout(() => {
            if (editEditorRef.value) {
              editEditorRef.value.setEditorContent(res.activityContent);
            }
          }, 100);
        }
      } else {
        proxy.$msg.error("活动数据为空");
      }
    })
    .catch((error) => {
      console.error("加载活动详情失败:", error);
      const errorMsg =
        error?.response?.data?.message ||
        error?.message ||
        "加载活动详情失败，请重试";
      proxy.$msg.error(errorMsg);
    })
    .finally(() => {
      editSpinLoading.value = false;
    });
};

// 取消编辑
const cancelEdit = () => {
  showEditForm.value = false;
  currentEditActivityId.value = null;
  // 重置表单数据
  Object.keys(editForm).forEach((key) => {
    if (key === "activityTop") {
      editForm[key] = proxy.yesNo.no.key;
    } else {
      editForm[key] = null;
    }
  });
  // 清空编辑器内容
  if (editEditorRef.value) {
    editEditorRef.value.setEditorContent("");
  }
};

// 保存编辑
const saveEdit = () => {
  // 检查编辑器是否存在
  if (!editEditorRef.value) {
    proxy.$msg.error("编辑器未初始化完成，请稍后重试");
    return;
  }

  // 获取富文本数据
  editForm.activityContent = editEditorRef.value.getEditorContent();

  // 验证富文本内容
  if (
    !editForm.activityContent ||
    editForm.activityContent.trim() === "" ||
    editForm.activityContent === "<p></p>"
  ) {
    proxy.$msg.error("活动内容不能为空");
    return;
  }

  // 表单验证
  editFormRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    editSpinLoading.value = true;

    // 区分添加和更新操作
    const isAdd = currentEditActivityId.value === null;
    const apiCall = isAdd
      ? addActivityApi(editForm)
      : updateActivityByActivityIdApi(editForm);
    const successMsg = isAdd ? "添加活动成功" : "更新活动成功";
    const errorMsg = isAdd ? "添加活动失败，请重试" : "更新活动失败，请重试";

    apiCall
      .then((res) => {
        proxy.$msg.success(successMsg);
        cancelEdit();
        // 刷新列表
        getPageList(false);
      })
      .catch((error) => {
        console.error(isAdd ? "添加活动失败:" : "更新活动失败:", error);
        const finalErrorMsg =
          error?.response?.data?.message || error?.message || errorMsg;
        proxy.$msg.error(finalErrorMsg);
      })
      .finally(() => {
        editSpinLoading.value = false;
      });
  });
};
//表格行数据 "查看" -> 点击
const detailBtnClick = (activityId) => {
  modal.visible = true;
  modal.title = "查看活动";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    activityId: activityId,
  };
  modal.component = shallowRef(ActivityDetail);
};
//删除确认弹窗 -> 确认
const deleteConfirmVisible = ref(false);
//表格行数据 "删除" -> 点击
const deleteBtnClick = (selectedKeys) => {
  if (selectedKeys.length === 0) {
    proxy.$msg.error("请选择要删除的活动");
    return;
  }
  deleteConfirmVisible.value = true;
};
//表格行数据 "删除" -> 确认
const deleteBtnOkClick = (activityId) => {
  deleteActivityByActivityIdApi(activityId).then(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    //刷新列表
    getPageList();
  });
};
const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
  selectedKeys.value = [];
};
//删除确认弹窗 -> 确认
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;
  let activityIds = [];
  selectedKeys.value.map((activityId) => {
    activityIds.push(activityId);
  });
  // 批量删除功能暂时注释，需要后端支持
  // deleteActivityByActivityIdApi(activityIds).then(() => {
  //   proxy.$msg.success(proxy.operationType.delete.success);
  //   //刷新列表
  //   selectedKeys.value = [];
  //   getPageList();
  // });
};

const onOk = () => {
  modal.visible = false;
  //查询数据列表
  getPageList();
};
//模态框 -> 取消
const onCancel = () => {
  modal.visible = false;
};

//查询数据列表
getPageList();
</script>

<style scoped></style>
